// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package handler

import (
	"context"

	"github.com/kumose/fn"
	logprinter "github.com/kumose/kmopt/pkg/logger/printer"
)

// errorMessage is used for error response
type errorMessage struct {
	Status  string `json:"status"`
	Message string `json:"message"`
}

func init() {
	fn.SetErrorEncoder(func(ctx context.Context, err error) any {
		logprinter.Debugf("Response an error message to client")
		if e, ok := err.(statusError); ok {
			logprinter.Debugf("Response status error to client: %s", e.Error())
			return &errorMessage{
				Status:  e.Status(),
				Message: e.Error(),
			}
		}
		logprinter.Debugf("Unknow error occurred: %s", err.Error())
		return &errorMessage{
			Status:  "UNKNOWN_ERROR",
			Message: "make sure your request is valid",
		}
	})
}
